import { useUserStore } from '@/stores/modules/user';
import { LOGIN_NAME, REGISTER_NAME } from '@/router/constant';
import NProgress from 'nprogress';
import { useKeepAliveStore } from '@/stores';

const defaultRoutePath = '/dashboard';
NProgress.configure({ showSpinner: false });
export function createRouterGuards(router, whiteNameList) {
  // 路由守卫
  router.beforeEach(async (to, from, next) => {
    NProgress.start();

    const userStore = useUserStore();
    const token = localStorage.getItem('token');
    // 不需要登录的页面
    if (whiteNameList.includes(to.name)) {
      if (token && userStore.isLoggedIn) {
        // 已登录，跳转到首页
        next();
      } else {
        next();
      }
      return;
    }

    // 需要登录的页面
    if (!token) {
      // 没有token，跳转到登录页
      next({ name: LOGIN_NAME });
      return;
    }

    // 有token但未加载用户信息
    if (!userStore.userInfo) {
      try {
        // 设置token到store
        userStore.setToken(token);

        // 获取用户信息并生成动态路由
        const userInfo = await userStore.getUserProfile();
        userStore.setUserInfo(userInfo);
        userStore.generateRoutes(userInfo.menus);
        // 重新导航到目标路由
        next({ ...to, replace: true });
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 获取用户信息失败，清除token并跳转到登录页
        userStore.clearUserInfo();
        next('/login');
      }
    } else {
      next();
    }
  });

  router.afterEach((to, from, failure) => {
    if (to.meta?.title) {
      // 设置网页标题
      document.title = to.meta.title;
    }

    const keepAliveStore = useKeepAliveStore();
    const userStore = useUserStore();
    if (userStore.isLoggedIn) {
      keepAliveStore.add(to.name);
    } else {
      keepAliveStore.clear();
    }

    // 关闭进度条
    NProgress.done();
  });
}
